import axios from 'axios';
import { Notification } from 'element-ui';

import router from '../router/index';

const urlMaps = {
    development: 'http://localhost:10227/api',
    production: 'https://api.uzxiao.com/api',
};

const request = axios.create({
    baseURL: urlMaps[process.env.NODE_ENV],
    timeout: 20000,
    headers: {
        'Content-Type': 'application/json',
    },
});

// 请求拦截器
request.interceptors.request.use(
    (config) => {
        config.headers['usertype'] = 1;
        const token = localStorage.getItem('token');
        if (token) {
            config.headers['Authorization'] = `Bearer ${token}`;
        }
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

// 响应拦截器
request.interceptors.response.use((response) => {
    const code = response.data.code;
    if (response.data instanceof Blob) {
        // 文件下载
        return response.data;
    }
    if (code === 502) {
        localStorage.removeItem("token");
        localStorage.removeItem("userInfo");
        router.push("/login");
        Notification.error({ title: '请求失败', message: '登录过期，请重新登录' });
        return response.data;
    }

    if (code !== 200) {
        Notification.error({ title: '请求失败', message: response.data.msg || '请求失败，请稍后重试' });
        return response.data;
    }
    return response.data;
},
    (error) => {
        console.error('请求失败:', error);
        return Promise.reject(error);
    }
);
// GET 请求
export const get = (url, params = {}, configs = {}) => {
    return request({
        url,
        method: 'get',
        params,
        ...configs,
    });
};

// POST 请求
export const post = (url, data = {}, configs = {}) => {
    return request({
        url,
        method: 'post',
        data,
        ...configs,
    });
};

// PUT 请求
export const put = (url, data = {}, configs = {}) => {
    return request({
        url,
        method: 'put',
        data,
        ...configs,
    });
};

// DELETE 请求
export const del = (url, params = {}, configs = {}) => {
    return request({
        url,
        method: 'delete',
        params,
        ...configs,
    });
};
